<template>
	<view class="container">
    <view class="header">
      <view class="title">地区选择</view>
					</view>

    <!-- 当前位置和重新定位 -->
    <view class="location-bar">
      <view class="location-info">
        <text class="location-label">当前位置：</text>
        <text class="location-value" v-if="currentLocation">{{ formatLocation(currentLocation) }}</text>
        <text class="location-value" v-else>未获取位置</text>
				</view>
      <view class="relocation-btn" @tap="reLocate">
        <uni-icons type="refresh" size="14" color="#4397FF"></uni-icons>
        <text>重新定位</text>
			</view>
		</view>

    <!-- 固定高度的三列布局选择器 -->
    <view class="columns-container">
      <!-- 省份列表 -->
      <scroll-view 
        scroll-y="true" 
        class="column province-column" 
        :show-scrollbar="false"
        :scroll-with-animation="true"
        :scroll-top="provinceScrollTop"
      >
        <view class="column-content">
          <view 
            v-for="(province, index) in provinces" 
            :key="index"
            class="column-item"
            :class="{ active: selectedProvince && selectedProvince.id === province.id }"
            @tap="selectProvince(province)"
            :id="`province-${province.id}`"
          >
            {{ province.name }}
					</view>
				</view>
			</scroll-view>

      <!-- 城市列表 -->
      <scroll-view 
        scroll-y="true" 
        class="column city-column" 
        :show-scrollbar="false"
        :scroll-with-animation="true"
        :scroll-top="cityScrollTop"
      >
        <view class="column-content">
          <view 
            v-for="(city, index) in cities" 
            :key="index"
            class="column-item"
            :class="{ active: selectedCity && selectedCity.id === city.id }"
            @tap="selectCity(city)"
            :id="`city-${city.id}`"
          >
            {{ city.name }}
          </view>
          <view class="empty-notice" v-if="cities.length === 0">请选择省份</view>
        </view>
      </scroll-view>

      <!-- 区县列表 -->
      <scroll-view 
        scroll-y="true" 
        class="column district-column" 
        :show-scrollbar="false"
        :scroll-with-animation="true"
        :scroll-top="districtScrollTop"
      >
        <view class="column-content">
          <view 
            v-for="(district, index) in districts" 
            :key="index"
            class="column-item"
            :class="{ active: selectedDistrict && selectedDistrict.id === district.id }"
            @tap="selectDistrict(district)"
            :id="`district-${district.id}`"
          >
            {{ district.name }}
				</view>
          <view class="empty-notice" v-if="districts.length === 0">请选择城市</view>
			</view>
      </scroll-view>
		</view>
	</view>
</template>

<script>
import { getAllCityList } from '@/apis/index'

// 常量定义
const DIRECT_CITIES = ['北京市', '上海市', '天津市', '重庆市']
const AMAP_KEY = '76cf898f09802d17efbf043b174b385c'

export default {
	name: 'YzbCitySelect',
	
	data() {
		return {
      imgUrl: "",
      // 省市区数据
      provinces: [], // 省级数据
      cities: [], // 市级数据
      districts: [], // 区县级数据
      
      // 当前选中的数据
      selectedProvince: null,
      selectedCity: null,
      selectedDistrict: null,
      
      // 保存接口返回的原始数据
      rawData: null,
      
      // 滚动位置
      provinceScrollTop: 0,
      cityScrollTop: 0,
      districtScrollTop: 0,
      
      // 当前定位位置
      currentLocation: null,
      locating: false,
    };
  },

  computed: {
    isDirectCity() {
      return this.selectedProvince ? DIRECT_CITIES.includes(this.selectedProvince.name) : false
    }
  },

  created() {
    this.initComponent().then(() => {
      this.$nextTick(() => {
        this.initLocation()
      })
    })
  },

  mounted() {
    this.preventPageScroll()
  },

  beforeDestroy() {
    this.restorePageScroll()
  },

	methods: {
    // 初始化组件
    async initComponent() {
      this.initImageUrl()
      await this.getProvinceList()
      this.loadSavedLocation()
    },

    // 初始化图片URL
    initImageUrl() {
      if (this.$mConfig?.imageUrl) {
        this.imgUrl = this.$mConfig.imageUrl
      }
    },

    // 加载保存的位置信息
    loadSavedLocation() {
      const savedLocation = uni.getStorageSync('savedLocation')
      if (savedLocation) {
        console.log('找到保存的位置信息:', savedLocation)
        this.currentLocation = savedLocation
        this.selectLocationFromSaved(savedLocation)
      }
    },

    // 防止页面滚动
    preventPageScroll() {
      document.body.style.overflow = 'hidden'
    },

    // 恢复页面滚动
    restorePageScroll() {
      document.body.style.overflow = ''
    },

    // 初始化位置信息
    initLocation() {
      if (this.currentLocation) {
        // 有当前位置，直接回显
        this.selectLocationFromSaved(this.currentLocation)
      } else {
        // 没有当前位置，重新定位
        this.reLocate()
      }
    },

    // 获取当前位置（只做重新定位）
    getCurrentLocation() {
      this.reLocate()
    },

    // 重新定位
    async reLocate() {
      if (this.locating) return
      this.locating = true

      try {
        const location = await this.getLocation()
        const locationDetail = await this.getLocationDetail(location)
        this.updateLocationInfo(locationDetail)
      } catch (error) {
        console.error('定位失败:', error)
      } finally {
        this.locating = false
        uni.hideLoading()
      }
    },

    // 获取位置
    getLocation() {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02',
          success: resolve,
          fail: reject
        })
      })
    },

    // 获取位置详情
    getLocationDetail({ longitude, latitude }) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: 'https://restapi.amap.com/v3/geocode/regeo',
          data: {
            key: AMAP_KEY,
            location: `${longitude},${latitude}`,
            extensions: 'base',
            output: 'json'
          },
          success: res => {
            if (res.data?.status === '1' && res.data.regeocode) {
              resolve(this.formatLocationDetail(res.data.regeocode, longitude, latitude))
				} else {
              reject(new Error('获取位置详情失败'))
            }
          },
          fail: reject
        })
      })
    },

    // 格式化位置详情
    formatLocationDetail(regeocode, longitude, latitude) {
      const { addressComponent } = regeocode
      const cityName = this.getCityName(addressComponent)
      
      return {
        latitude,
        longitude,
        pcity: addressComponent.province,
        city: cityName,
        district: addressComponent.district || '',
        adcode: addressComponent.adcode,
        citycode: addressComponent.citycode,
        formatted_address: regeocode.formatted_address || ''
      }
    },

    // 获取城市名称
    getCityName(addressComponent) {
      if (Array.isArray(addressComponent.city) && addressComponent.city.length === 0) {
        return addressComponent.province
      }
      return typeof addressComponent.city === 'string' ? addressComponent.city : addressComponent.province
    },

    // 更新位置信息
    updateLocationInfo(location) {
      this.currentLocation = location
      if (getApp().globalData) {
        getApp().globalData.currentLocation = location
      }
      uni.setStorageSync('savedLocation', location)
      this.selectLocationFromSaved(location)
    },

    // 获取省份列表
    async getProvinceList() {
      uni.showLoading({ title: "加载中..." })
      try {
        const res = await getAllCityList()
        if (res?.data?.length > 0) {
          this.rawData = res.data
          this.provinces = this.formatProvinceList(res.data)
          console.log('省份列表加载完成:', this.provinces.length)
        }
      } catch (error) {
        console.error('获取省份列表失败:', error)
      } finally {
        uni.hideLoading()
      }
    },

    // 格式化省份列表
    formatProvinceList(data) {
      const provinces = []
      data.forEach(letterGroup => {
        if (letterGroup.data?.length > 0) {
          letterGroup.data.forEach(province => {
            provinces.push({
              id: province.id,
              name: province.name,
              data: province.data || []
            })
          })
        }
      })
      return provinces.sort((a, b) => a.name.localeCompare(b.name, 'zh'))
    },

    // 选择省份
    selectProvince(province) {
      console.log("选择省份：", province)
      this.selectedProvince = province
      this.selectedCity = null
      this.selectedDistrict = null
      this.districts = []
      this.resetScrollPosition()
      this.updateCityList(province)
      
    },

    // 重置滚动位置
    resetScrollPosition() {
      this.cityScrollTop = 0
      this.districtScrollTop = 0
    },

    // 更新城市列表
    updateCityList(province) {
      if (!province.data?.length) {
        this.cities = []
        return
      }

      const filteredCities = province.data.filter(city => 
        city.name !== "市辖区" && city.name !== "县"
      )

      const allProvince = {
        id: province.id + '_all',
        name: `全${province.name.replace('市', '')}`,
        isAll: true,
        parentId: province.id
      }

      this.cities = [allProvince, ...filteredCities]

      if (this.isDirectCity && this.cities.length <= 1) {
        this.cities.push({
          id: province.id,
          name: province.name.substring(0, 2),
          parentId: province.id
        })
      }
    },

    // 选择城市
    selectCity(city) {
      console.log("选择城市：", city)
      this.selectedCity = city
      this.selectedDistrict = null
      this.districtScrollTop = 0

      if (city.isAll) {
        this.handleAllCitySelection()
        return
      }

      if (this.isDirectCity) {
        this.getDirectCityDistricts(this.selectedProvince.id)
      } else {
        this.getDistrictsFromRawData(city.id)
      }
    },

    // 处理选择"全市"的情况
    handleAllCitySelection() {
      this.districts = [{
        id: this.selectedProvince.id + '_all_district',
        name: `全${this.selectedProvince.name.replace('市', '')}`,
        isAll: true,
        parentId: this.selectedProvince.id
      }]
    },

    // 获取直辖市下的所有市辖区
    getDirectCityDistricts(provinceId) {
      if (!this.rawData || !provinceId) return

      const province = this.findProvinceInRawData(provinceId)
      if (!province) return

      const cityDistrict = province.data.find(city => city.name === "市辖区")
      if (!cityDistrict?.data?.length) return

      const allCity = {
        id: cityDistrict.id + '_all',
        name: `全${this.selectedProvince.name.replace('市', '')}`,
        isAll: true,
        parentId: cityDistrict.id
      }

      this.districts = [allCity, ...cityDistrict.data]
      console.log("直辖市区县数据：", this.districts)
    },

    // 从原始数据中查找省份
    findProvinceInRawData(provinceId) {
      for (const letterGroup of this.rawData) {
        if (letterGroup.data?.length > 0) {
          const province = letterGroup.data.find(p => p.id === provinceId)
          if (province) return province
        }
      }
      return null
    },

    // 从原始数据中获取区县列表
    getDistrictsFromRawData(cityId) {
      if (!this.rawData || !cityId) return

      const city = this.findCityInRawData(cityId)
      if (!city?.data?.length) return

      const allCity = {
        id: city.id + '_all',
        name: `全${city.name.replace('市', '').replace('地区', '')}`,
        isAll: true,
        parentId: city.id
      }

      this.districts = [allCity, ...city.data]
      console.log("区县数据：", this.districts)
    },

    // 从原始数据中查找城市
    findCityInRawData(cityId) {
      for (const letterGroup of this.rawData) {
        if (letterGroup.data?.length > 0) {
          for (const province of letterGroup.data) {
            if (province.data?.length > 0) {
              const city = province.data.find(c => c.id === cityId)
              if (city) return city
            }
          }
        }
      }
      return null
    },

    // 选择区县
    selectDistrict(district) {
      console.log("选择区县：", district)
      this.selectedDistrict = district
      
      const locationData = this.createLocationData(district)
      this.updateCurrentLocation(locationData)
      this.$emit("selectLocation", locationData)
      uni.switchTab({
        url:'/pages/index/index'
      })
    },

    // 创建位置数据
    createLocationData(district) {
      const baseData = {
        province: {
          id: this.selectedProvince.id,
          name: this.selectedProvince.name
        }
      }

      if (district.isAll) {
        if (this.selectedCity.isAll) {
          return {
            ...baseData,
            isAll: true,
            level: 'province',
            fullAddress: this.selectedProvince.name
          }
        }
        return {
          ...baseData,
          city: {
            id: this.selectedCity.id,
            name: this.selectedCity.name
          },
          isAll: true,
          level: 'city',
          fullAddress: `${this.selectedProvince.name} ${this.selectedCity.name}`
        }
      }

      return {
        ...baseData,
        city: {
          id: this.selectedCity.id,
          name: this.selectedCity.name
        },
        district: {
          id: district.id,
          name: district.name
        },
        level: 'district',
        fullAddress: `${this.selectedProvince.name} ${this.selectedCity.name} ${district.name}`
      }
    },

    // 更新当前位置信息
    updateCurrentLocation(locationData) {
      const currentLocation = {
        pcity: locationData.province.name,
        city: locationData.city ? locationData.city.name : locationData.province.name,
        district: locationData.district ? locationData.district.name : '',
        formatted_address: locationData.fullAddress || ''
      }
      
      this.currentLocation = currentLocation
      if (getApp().globalData) {
        getApp().globalData.currentLocation = currentLocation
      }
      uni.setStorageSync('savedLocation', currentLocation)
    },

    // 根据保存的位置信息选中对应的省市区
    selectLocationFromSaved(location) {
      if (!location || !this.rawData) {
        console.log('位置信息或原始数据不存在，无法回显')
        return
      }
      console.log('开始回显位置:', location)

      if (this.provinces.length === 0) {
        console.log('省份列表未加载，等待加载...')
        setTimeout(() => this.selectLocationFromSaved(location), 100)
        return
      }

      this.waitForProvinces(location)
    },

    // 等待省份列表加载完成
    waitForProvinces(location) {
      const province = this.provinces.find(p => p.name === location.pcity)
      if (province) {
        console.log('找到省份:', province)
        this.selectProvince(province)
        this.$nextTick(() => {
          this.waitForCities(location, province)
        })
      } else {
        console.log('未找到省份:', location.pcity)
      }
    },

    // 等待城市列表加载完成
    waitForCities(location, province) {
      if (this.cities.length === 0) {
        console.log('城市列表未加载，等待加载...')
        setTimeout(() => this.waitForCities(location, province), 100)
        return
      }

      const city = this.isDirectCity
        ? this.cities.find(c => c.name === province.name.substring(0, 2))
        : this.cities.find(c => c.name === location.city)

      if (city) {
        console.log('找到城市:', city)
        this.selectCity(city)
        this.$nextTick(() => {
          this.waitForDistricts(location, province, city)
        })
      } else {
        console.log('未找到城市:', location.city, '可用的城市:', this.cities)
      }
    },

    // 等待区县列表加载完成
    waitForDistricts(location, province, city) {
      if (this.districts.length === 0) {
        console.log('区县列表未加载，等待加载...')
        setTimeout(() => this.waitForDistricts(location, province, city), 100)
        return
      }

      const district = this.districts.find(d => d.name === location.district)
      if (district) {
        console.log('找到区县:', district)
        this.selectedDistrict = district
        this.$nextTick(() => {
          this.updateCurrentLocation({
            province: {
              id: province.id,
              name: province.name
            },
            city: {
              id: city.id,
              name: city.name
            },
            district: {
              id: district.id,
              name: district.name
            },
            level: 'district',
            fullAddress: `${province.name} ${city.name} ${district.name}`
          })
        })
      } else {
        console.log('未找到区县:', location.district, '可用的区县:', this.districts)
      }
    },

    // 格式化位置显示
    formatLocation(location) {
      if (!location) return '未知位置';
      
      let result = '';
      
      // 优先使用格式化地址，但只提取省市区部分
      if (location.formatted_address) {
        const address = location.formatted_address;
        
        // 正则匹配获取省市区部分（通常格式为"省市区街道/乡镇..."）
        const regex = /(.*?[省市])(.*?[市区县])(.*?[区县])?/;
        const matches = address.match(regex);
        
        if (matches) {
          // 只使用匹配到的省市区部分
          let provinceCityDistrict = '';
          if (matches[1]) {
            // 省/直辖市
            provinceCityDistrict += matches[1].replace(/市$/, '');
          }
          
          if (matches[2]) {
            // 市/区
            const city = matches[2].replace(/市$/, '');
            // 避免直辖市重复
            if (!provinceCityDistrict.includes(city)) {
              provinceCityDistrict += ' ' + city;
            }
          }
          
          if (matches[3]) {
            // 区/县
            const district = matches[3].replace(/[区县]$/, '');
            provinceCityDistrict += ' ' + district;
          }
          
          if (provinceCityDistrict) {
            return provinceCityDistrict;
          }
        }
        
        // 如果正则匹配失败，则使用简单的分割方法
        const mainParts = address.split('街道')[0].split('乡镇')[0].split('镇')[0].split('社区')[0];
        return mainParts;
      }
      
      // 如果没有格式化地址，则使用分开的字段
      if (location.pcity) {
        // 处理省份
        let provinceName = location.pcity;
        // 移除"市"后缀（针对直辖市）
        if (provinceName.endsWith('市')) {
          provinceName = provinceName.substring(0, provinceName.length - 1);
        }
        result += provinceName;
      }
      
      // 处理城市
      if (location.city && location.city !== location.pcity) {
        let cityName = location.city;
        // 移除"市"后缀
        if (cityName.endsWith('市')) {
          cityName = cityName.substring(0, cityName.length - 1);
        }
        // 避免直辖市重复
        if (!result.includes(cityName)) {
          result += ' ' + cityName;
        }
      }
      
      // 处理区县
      if (location.district) {
        let districtName = location.district;
        // 移除"区"、"县"等后缀
        if (districtName.endsWith('区') || districtName.endsWith('县') || districtName.endsWith('市')) {
          districtName = districtName.substring(0, districtName.length - 1);
        }
        result += ' ' + districtName;
      }
      
      return result || '未知位置';
    },
	}
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
		display: flex;
  flex-direction: column;
  z-index: 999;
}

.header {
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
  text-align: center;
  flex-shrink: 0;
}

.title {
		font-size: 32rpx;
  font-weight: bold;
		color: #333;
}

.location-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 30rpx;
  background-color: #f8f8f8;
  border-bottom: 1rpx solid #eee;
  flex-shrink: 0;
}

.location-info {
  display: flex;
  align-items: center;
}

.location-label {
  font-size: 24rpx;
  color: #666;
}

.location-value {
  font-size: 24rpx;
  color: #333;
		font-weight: 500;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.relocation-btn {
  display: flex;
			align-items: center;
  padding: 8rpx 16rpx;
  border-radius: 30rpx;
  background-color: rgba(67, 151, 255, 0.1);
  color: #4397FF;
				font-size: 24rpx;
			}

.relocation-btn text {
  margin-left: 8rpx;
	}

.columns-container {
		display: flex;
  flex: 1;
  overflow: hidden;
}

.column {
  flex: 1;
  height: 100%;
  position: relative;
}

.column-content {
  width: 100%;
}

.province-column {
  background-color: #f3f3f3;
  border-right: 1rpx solid #f0f0f0;
}

.city-column {
  background-color: #f8f8f8;
  border-right: 1rpx solid #f0f0f0;
}

.district-column {
  background-color: #fff;
}

.column-item {
  padding: 25rpx 24rpx;
  font-size: 26rpx;
		color: #333;
  position: relative;
  border-bottom: 1rpx solid #f0f0f0;
}

.column-item.active {
  color: #3e8fff;
  background-color: #fff;
  font-weight: 500;
}

.province-column .column-item.active::after {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 36rpx;
  background-color: #3e8fff;
}

.district-column .column-item.active::after {
  content: '✓';
  position: absolute;
  right: 24rpx;
  top: 50%;
  transform: translateY(-50%);
  color: #3e8fff;
  font-weight: bold;
}

.empty-notice {
  padding: 40rpx 0;
	text-align: center;
  color: #999;
  font-size: 26rpx;
}
</style>
